package com.alogic.nginx.xscript;


import com.alogic.xscript.AbstractLogiclet;
import com.alogic.xscript.ExecuteWatcher;
import com.alogic.xscript.Logiclet;
import com.alogic.xscript.LogicletContext;
import com.alogic.xscript.doc.XsObject;
import com.anysoft.util.BaseException;
import com.anysoft.util.Properties;
import com.anysoft.util.PropertiesConstants;
import org.apache.commons.codec.digest.DigestUtils;

/**
 * 生成内容的MD5编码
 * @author yyduan
 * @since 1.6.12.25 [20190311 duanyy] <br>
 */
public class NginxConentMd5 extends AbstractLogiclet {
	
	/**
	 * 上下文id
	 */
	protected String pid = "$nginx-conf";

	protected String id = "$ngix-md5";
	
	public NginxConentMd5(String tag, Logiclet p) {
		super(tag, p);
	}

	@Override
	public void configure(Properties p){
		super.configure(p);
		
		pid = PropertiesConstants.getString(p, "pid", pid,true);
		id = PropertiesConstants.getRaw(p,"id",id);
	}
	
	@Override
	protected void onExecute(XsObject root, XsObject current, final LogicletContext ctx, final ExecuteWatcher watcher){
		StringBuffer content = ctx.getObject(pid);
		if (content == null){
			throw new BaseException("core.e1001","It must be in a ngx-conf context,check your script.");
		}

		ctx.SetValue(id, DigestUtils.md5Hex(content.toString()));
	}

}